package com.padgett.resourcemanagement.invoice;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.padgett.resourcemanagement.data.ClientDAO;
import com.padgett.resourcemanagement.listener.InvoiceServletContext;
import com.padgett.resourcemanagement.util.DateUtil;

/**
 * Save invoice.
 * 
 * @author andyleung
 * 
 */
@SuppressWarnings("serial")
public class AjaxSaveInvoiceLineItemServlet extends HttpServlet{
	private static final Logger logger=Logger.getLogger(AjaxSaveInvoiceLineItemServlet.class.getName());
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String invoiceLineItemId=req.getParameter("invoiceLineItemId");
		String invoiceId=req.getParameter("invoiceId");
		String serviceId=req.getParameter("serviceId");
		String amountString=req.getParameter("Amount");
		String description=req.getParameter("Description");
		String taxable=req.getParameter("Taxable");
		// Client Number and Legal Number must be presented to generate a unique key
		UserService userService=UserServiceFactory.getUserService();
		User user=userService.getCurrentUser();
		Key invoiceItemKey=new KeyFactory.Builder(KeyFactory.stringToKey(invoiceId))
		.getKey();
		Entity invoiceLineItem=null;
		if(invoiceLineItemId==null||invoiceLineItemId.trim().isEmpty()){
			invoiceLineItem=new Entity("InvoiceLineItem",invoiceItemKey);
			invoiceLineItem.setUnindexedProperty("CreatedBy", user.getNickname());
			invoiceLineItem.setUnindexedProperty("CreatedDate", new Date(System.currentTimeMillis()));
		}else{
			invoiceLineItem=ClientDAO.loadEntity(KeyFactory.stringToKey(invoiceLineItemId));
		}
		
		invoiceLineItem.setUnindexedProperty("LastModifiedBy", user.getNickname());
		invoiceLineItem.setUnindexedProperty("LastModifiedDate", new Date(System.currentTimeMillis()));
		invoiceLineItem.setProperty("Service", KeyFactory.stringToKey(serviceId));
		// Get service due date using Service ID
		Entity service=ClientDAO.loadEntity(KeyFactory.stringToKey(serviceId));
		invoiceLineItem.setUnindexedProperty("ServiceRendered", (DateUtil.formatDate(((Date)service.getProperty("DueDate")), DateUtil.MONTH_DATE_FORMAT)));
		invoiceLineItem.setUnindexedProperty("Taxable", Boolean.valueOf(taxable));
		double amount=Double.parseDouble(amountString);
		invoiceLineItem.setUnindexedProperty("Amount", amount);
		double tax=0.0;
		if(Boolean.valueOf(taxable)){
			tax=new Double(amount*InvoiceServletContext.HST);
		}
		invoiceLineItem.setUnindexedProperty("Tax", tax);
		invoiceLineItem.setUnindexedProperty("Total", amount+tax);
		invoiceLineItem.setUnindexedProperty("Description", new Text(description));
		Key savedKey=ClientDAO.saveEntity(invoiceLineItem);
		// Mark this service as billed
		service.setProperty("Billed", Boolean.TRUE);
		ClientDAO.saveEntity(service);
		JSONObject response=new JSONObject();
		try {
			if(savedKey!=null){
				response.put("success", "true");
				response.put("invoiceId", KeyFactory.keyToString(savedKey));
			}else{
				response.put("success", "false");
				response.put("error", "Unable to save invoice line item at the moment.");
			}
		} catch (JSONException e) {
			logger.severe(e.getMessage());
		}
		resp.getWriter().write(response.toString());
	}

}
